package com.jdy.haoduoaiteacher.activity;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.LeMachine;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.scan.camera.CameraManager;
import com.jdy.haoduoaiteacher.scan.decode.Bitmap2QR;
import com.jdy.haoduoaiteacher.scan.decode.CaptureActivityHandler;
import com.jdy.haoduoaiteacher.scan.decode.InactivityTimer;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.LeConfig;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.ViewfinderView;
import com.jdy.haoduoaiteacher.widget.BindSuccessOneBtnDialog;
import com.ycsj.goldmedalnewconcept.R;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Vector;

//import com.jdy.haoduoaiteacher.R;

public class CaptureActivity extends BaseActivity implements Callback {
  private CaptureActivityHandler handler;

  private ViewfinderView viewfinderView;

  private boolean hasSurface;

  private Vector<BarcodeFormat> decodeFormats;

  private String characterSet;

  private InactivityTimer inactivityTimer;

  private MediaPlayer mediaPlayer;

  private boolean playBeep;

  private static final float BEEP_VOLUME = 0.10f;

  private boolean vibrate;

  private LeUser mLeUser;

  private ImageView mBackImageView;

  private ImageView mPickImageView;

  private static final int SELECT_PHOTO = 100;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.scan_layout);

    hideTitleView();

    mLeUser = MyTeacherApp.getInstance().getUserTeacher();

    mBackImageView = (ImageView) findViewById(R.id.cameraScanBackImageView);

    mBackImageView.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {

        finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      }
    });

    mPickImageView = (ImageView) findViewById(R.id.selecteImageFromGalleryImageView);

    mPickImageView.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {

        pickFromGallery();
      }
    });

    CameraManager.init(getApplication());
    viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

    hasSurface = false;
    inactivityTimer = new InactivityTimer(this);

  }

  private void pickFromGallery() {
    try {
      Intent intent = new Intent(Intent.ACTION_PICK, null);
      intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
          "image/*");
      startActivityForResult(intent, SELECT_PHOTO);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    } catch (ActivityNotFoundException e) {
      Toast.makeText(CaptureActivity.this, "找不到系统相册！", Toast.LENGTH_LONG)
          .show();

    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch (requestCode) {
    case SELECT_PHOTO:
      if (resultCode == RESULT_OK) {
        // this.mResultURI = imageReturnedIntent.getData();

        Result result = null;
        try {
          InputStream is = getContentResolver().openInputStream(
              imageReturnedIntent.getData());
          result = Bitmap2QR.scanningImage(is);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }

        if (result != null) {
          handleDecode(result, null);
        } else {
          Toast.makeText(CaptureActivity.this, "识别失败", Toast.LENGTH_LONG)
              .show();
        }
      }
    }
  }

  @SuppressWarnings("deprecation")
  @Override
  protected void onResume() {
    super.onResume();
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    if (hasSurface) {
      initCamera(surfaceHolder);
    } else {
      surfaceHolder.addCallback(this);
      surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    decodeFormats = null;
    characterSet = null;

    playBeep = true;
    AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
      playBeep = false;
    }
    initBeepSound();
    vibrate = true;

  }

  @Override
  protected void onPause() {
    super.onPause();
    if (handler != null) {
      handler.quitSynchronously();
      handler = null;
    }
    CameraManager.get().closeDriver();
  }

  @Override
  protected void onDestroy() {
    inactivityTimer.shutdown();
    super.onDestroy();
  }

  /**
   * 处理扫描结果
   *
   * @param result
   * @param barcode
   */
  public void handleDecode(Result result, Bitmap barcode) {
    inactivityTimer.onActivity();
    playBeepSoundAndVibrate();
    String resultStr = result.getText();
    if (resultStr.equals("")) {
      Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT)
          .show();
      CaptureActivity.this.finish();
    } else {
      Intent resultIntent = new Intent();
      Bundle bundle = new Bundle();
      bundle.putString("result", resultStr);
      resultIntent.putExtras(bundle);

      this.setResult(RESULT_OK, resultIntent);
      bindDevice(resultStr);
    }
  }

  private void bindSuccessTip(final String macId) {

    BindSuccessOneBtnDialog.Builder cdb = new BindSuccessOneBtnDialog.Builder(
        CaptureActivity.this).setTitle("设备绑定成功").setMessage("设备序列号：" + macId)
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();

            checkMacActivation(macId);
          }
        });
    BindSuccessOneBtnDialog cd = cdb.create();
    cd.setCancelable(false);
    cd.setCanceledOnTouchOutside(false);

    if (!isFinishing()) {
      cd.show();
    }
  }

  private int totalMonth;

  /**
   * 判断宝宝年龄
   */
  private void checkBabyAge() {
    LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
    if (lu != null && Tools.isNotEmpty(lu.machine)) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      try {
        Calendar bef = Calendar.getInstance();
        bef.setTime(sdf.parse(lu.machine.dob));

        int month = Calendar.getInstance().get(Calendar.MONTH)
            - bef.get(Calendar.MONTH);

        int year = Calendar.getInstance().get(Calendar.YEAR)
            - bef.get(Calendar.YEAR);

        totalMonth = year * 12 + month;
        if (totalMonth == 0) {
          totalMonth = 1;
        }

      } catch (Exception e) {
        // TODO: handle exception
      }
    }
  }

  private void doPageRoute() {
    checkBabyAge();

    if (LeConfig.isLogin) {

      Intent intent = new Intent(this, MainActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(intent);

//      if (LeConfig.isDeviceBinded) {
//        if (LeConfig.isInfoFilled) {
//
//          if (totalMonth >= (6 * 12)) {
//            Intent intent = new Intent(this, MainActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//            // Intent t = new Intent(this, AttractNewRepelActivity.class);
//            // startActivity(t);
//          } else {
//            Intent intent = new Intent();
//            intent.putExtra("registerflow", true);
//            intent.setClass(CaptureActivity.this, AbilityTestActivity.class);
//            startActivity(intent);
//          }
//
//          finish();
////          if (LeConfig.isDeviceActivated) {
////
////          } else {
////            // TODO
////          }
//        } else {
////          Intent t = new Intent(this, FillInfoPopupActivity.class);
////          startActivity(t);
////          finish();
//        }
//      } else {
//        // TODO
//      }
    } else {
      // TODO
    }
  }

  private void checkMacActivation(final String macId) {
    LeMachine macInfo = MyTeacherApp.getInstance().getBabyTeacher();

    if (macInfo != null) {
      // checkDeviceVersion(macInfo.version);

      if (Tools.isNotEmpty(macInfo.name)) {
        if (mLeUser != null && Tools.isNotEmpty(mLeUser.callname)
            && Tools.isNotEmpty(mLeUser.nickname)) {
         // LeConfig.isInfoFilled = true;
        }

        if (Tools.isNotEmpty(macInfo.activate)
            && !macInfo.activate.toString().equals("null")) {
//          LeConfig.isDeviceActivated = !macInfo.activate.is_expired;
//          LeConfig.expiredAt = macInfo.activate.expired_at;
        }
      }
    }

    doPageRoute();

    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

  }

  // public void checkDeviceVersion(String version) {
  // if (Tools.isNotEmpty(version)) {
  // try {
  // int currentDeviceVersion = Integer.valueOf(version.replaceAll("\\D+",
  // ""));
  // LeConfig.CURRENT_DEVICE_VERSION = currentDeviceVersion;
  // if (currentDeviceVersion < 201 && !LeConfig.DEBUG_MODE) {
  // LeConfig.isDeviceVersionMatch = false;
  // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
  // getApplicationContext()).setTitle("升级提示")
  // .setMessage("请更新您的小小班设备")
  // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  //
  // @Override
  // public void onClick(DialogInterface dialog, int which) {
  // dialog.dismiss();
  // }
  // });
  // CustomOneBtnDialog cd = cdb.create();
  // cd.setCancelable(false);
  // cd.setCanceledOnTouchOutside(false);
  // cd.show();
  // } else {
  // LeConfig.isDeviceVersionMatch = true;
  // }
  // } catch (NumberFormatException nfe) {
  // return;
  // }
  // }
  // }

  private void bindDevice(final String macId) {
    if (mLeUser != null && mLeUser.machine != null
        && !mLeUser.machine.toString().equals("null")) {
      MyTeacherApp.getInstance().setUser(mLeUser);
      Tools.saveLeUser(mLeUser);
    }

    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {

        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
         // LeConfig.isDeviceBinded = true;

          LeMachine macInfo = JsonSerializer.getInstance().deserialize(
              result.data, LeMachine.class);
          MyTeacherApp.getInstance().setBaby(macInfo);
          Tools.saveLeBaby(macInfo);

          LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
          if (lu != null) {
            lu.machine = macInfo; // );
          }

          bindSuccessTip(macInfo.id);

          Toast.makeText(getApplicationContext(), result.data,
              Toast.LENGTH_SHORT).show();
          CaptureActivity.this.finish();
          overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        } else {
          //LeConfig.isDeviceBinded = false;
          if (Tools.isNotNullStr(result.data)) {
            toastShow(result.data);

            if (result.data.contains("设备未注册")) {
//              CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
//                  CaptureActivity.this)
//                  .setTitle("温馨提示")
//                  .setMessage("绑定设备之前，请先确保您的小小班设备已经连上网络。")
//                  .setPositiveButton("确定",
//                      new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                          dialog.dismiss();
//                          Intent intent2 = new Intent(CaptureActivity.this,
//                              ConnectWifiActivity.class);
//                          intent2.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
//                              | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                          startActivity(intent2);
//                          overridePendingTransition(R.anim.push_left_in,
//                              R.anim.push_left_out);
//                        }
//                      });
//              CustomOneBtnDialog cd = cdb.create();
//              cd.setCancelable(false);
//              cd.setCanceledOnTouchOutside(false);
//              cd.show();
            }
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();

        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put("bind_code", macId);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequestEncrypt(HttpUtils.API_URL
            + HttpUtils.BIND_DEVICE_METHOD_POST, param_,
            HttpUtils.TAG_POST_REQUEST);
      }
    }).execute();
  }

  private void initCamera(SurfaceHolder surfaceHolder) {
    try {
      CameraManager.get().openDriver(surfaceHolder);
    } catch (IOException ioe) {
      return;
    } catch (RuntimeException e) {
      return;
    }
    if (handler == null) {
      handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
    }
  }

  @Override
  public void surfaceChanged(SurfaceHolder holder, int format, int width,
      int height) {

  }

  @Override
  public void surfaceCreated(SurfaceHolder holder) {
    if (!hasSurface) {
      hasSurface = true;
      initCamera(holder);
    }

  }

  @Override
  public void surfaceDestroyed(SurfaceHolder holder) {
    hasSurface = false;

  }

  public ViewfinderView getViewfinderView() {
    return viewfinderView;
  }

  public Handler getHandler() {
    return handler;
  }

  public void drawViewfinder() {
    viewfinderView.drawViewfinder();

  }

  private void initBeepSound() {
    if (playBeep && mediaPlayer == null) {
      // The volume on STREAM_SYSTEM is not adjustable, and users found it
      // too loud,
      // so we now play on the music stream.
      setVolumeControlStream(AudioManager.STREAM_MUSIC);
      mediaPlayer = new MediaPlayer();
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mediaPlayer.setOnCompletionListener(beepListener);

      AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
      try {
        mediaPlayer.setDataSource(file.getFileDescriptor(),
            file.getStartOffset(), file.getLength());
        file.close();
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
      } catch (IOException e) {
        mediaPlayer = null;
      }
    }
  }

  private static final long VIBRATE_DURATION = 200L;

  private void playBeepSoundAndVibrate() {
    if (playBeep && mediaPlayer != null) {
      mediaPlayer.start();
    }
    if (vibrate) {
      Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
      vibrator.vibrate(VIBRATE_DURATION);
    }
  }

  /**
   * When the beep has finished playing, rewind to queue up another one.
   */
  private final OnCompletionListener beepListener = new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
      mediaPlayer.seekTo(0);
    }
  };

}